//
//  LQPictureViewController.swift
//  picturePickerView
//
//  Created by 半缘君 on 15/12/18.
//  Copyright © 2015年 banyuanjun.cn. All rights reserved.
//

import UIKit
private let LQMAXPICTURECOUNT = 3
private let LQPictureViewCellID = "LQPictureViewCellID"

class LQPictureViewController: UICollectionViewController {
    
    /// 存储选择的照片
    lazy var selectedPictures = [UIImage]()
    var currentIndexPath : NSIndexPath?
    //MARK: -  构造方法
    init () {
        super.init(collectionViewLayout: LQPictureViewLayout())
        
    }
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //MARK: - 生命周期方法
    override func loadView() {
        super.loadView()
        collectionView?.backgroundColor = UIColor.lightGrayColor()
    }
    override func viewDidLoad() {
        super.viewDidLoad()
//        automaticallyAdjustsScrollViewInsets = false
        // Register cell classes
        self.collectionView!.registerClass(LQPictureViewCell.self, forCellWithReuseIdentifier: LQPictureViewCellID)

        // Do any additional setup after loading the view.
    }
    
    private class LQPictureViewLayout:UICollectionViewFlowLayout {
        private override func prepareLayout() {
            super.prepareLayout()
            let margin = UIScreen.mainScreen().scale * 8
            let w = (collectionView!.bounds.width - margin * 5) / 4
            itemSize = CGSize(width: w, height: w)
            sectionInset = UIEdgeInsets(top: margin, left: margin, bottom: 0, right: margin)
            minimumInteritemSpacing = margin
            minimumLineSpacing = margin
        }
    }
 
}
//MARK: - LQPictureViewControllerDataSource
extension LQPictureViewController {
    override func collectionView(collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {

        return selectedPictures.count + 1
    }
    
    override func collectionView(collectionView: UICollectionView, cellForItemAtIndexPath indexPath: NSIndexPath) -> UICollectionViewCell {
        let cell = collectionView.dequeueReusableCellWithReuseIdentifier(LQPictureViewCellID, forIndexPath: indexPath) as! LQPictureViewCell
        
        cell.pictureDelegate = self
        
        cell.image = indexPath.item < selectedPictures.count ?  selectedPictures[indexPath.item] : nil
        
        cell.hidden = (indexPath.item == LQMAXPICTURECOUNT)
        
        return cell
    }
}

//MARK: - LQPictureViewCellDelegate 实现
extension LQPictureViewController:LQPictureViewCellDelegate {
    @objc private func pictureViewCellDidClickAddButton(cell: LQPictureViewCell) {

        //push出imagePickerView
        let pictureVc = UIImagePickerController()
        if UIImagePickerController.isSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary) {
            self.presentViewController(pictureVc, animated: true, completion: nil)
        }
        //记录选中的cell的indexPath
        currentIndexPath = collectionView?.indexPathForCell(cell)

        //设置代理
        pictureVc.delegate = self
        
        
    }
    @objc private func pictureViewCellDidClickRemoveButton(cell: LQPictureViewCell) {

        //获取索引
        let index = collectionView?.indexPathForCell(cell)
        if index?.item >= selectedPictures.count {
            return
        }
        selectedPictures.removeAtIndex(index!.item)
        collectionView?.deleteItemsAtIndexPaths([index!])
        //如果选中的图片的个数比最大数-1小九不用reload了,不然会崩溃
        //当选中的图片是最大的个数的时候
        if selectedPictures.count < LQMAXPICTURECOUNT - 1{
            return
        }
        let newIndexPath = NSIndexPath(forItem: LQMAXPICTURECOUNT - 1, inSection: 0)
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(0.25 * Double( NSEC_PER_SEC))), dispatch_get_main_queue()) { () -> Void in
            
            self.collectionView?.reloadItemsAtIndexPaths([newIndexPath])
        }
        
    }
}
//MARK: - UIImagePickerControllerDelegate 代理实现
extension LQPictureViewController:UIImagePickerControllerDelegate,UINavigationControllerDelegate {
    func imagePickerController(picker: UIImagePickerController, didFinishPickingImage image: UIImage, editingInfo: [String : AnyObject]?) {
        //判断选中的是不是添加按钮,是添加的按钮就添加,不是就更改图片
        
       let image = image.scaleToWidth(600)
        if currentIndexPath?.item > selectedPictures.count - 1{
            selectedPictures.append(image)
        } else{
            selectedPictures[currentIndexPath!.item] = image
        }
        //退出imagePickerView
        dismissViewControllerAnimated(true, completion: nil)
        //刷新数据
//        self.collectionView?.insertItemsAtIndexPaths([currentIndexPath!])
        self.collectionView?.reloadData()
    }
}
//MARK: - LQPictureViewCellDelegate 定义
@objc
private protocol LQPictureViewCellDelegate{
    optional func pictureViewCellDidClickAddButton(cell:LQPictureViewCell)
    optional func pictureViewCellDidClickRemoveButton(cell:LQPictureViewCell)
}
//MARK: - LQPictureViewCell 定义
private class LQPictureViewCell:UICollectionViewCell {
    /// 代理
    weak var pictureDelegate:LQPictureViewCellDelegate?
    
    var image:UIImage? {
        didSet {
            
            addButton.setImage(image ?? UIImage(named: "compose_pic_add"), forState: UIControlState.Normal)
            
            removeButton.hidden = (image == nil)
            
        }
    }
    /// MARK: - 懒加载控件
    private lazy var addButton:UIButton = UIButton(backImageName: "compose_pic_add", imageName: nil)
    private lazy var removeButton:UIButton = UIButton(backImageName: "compose_photo_close", imageName: nil)

    //MARK: - 构造函数
    override init(frame: CGRect) {
        super.init(frame: frame)
        setupUI()
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    //MARK: -  添加子控件
    private func setupUI () {
        contentView.addSubview(addButton)
        contentView.addSubview(removeButton)
        
        addButton.frame = bounds
        removeButton.snp_makeConstraints { (make) -> Void in
            make.top.equalTo(contentView.snp_top)
            make.right.equalTo(contentView.snp_right)
        }
        addButton.addTarget(self, action: "clickAddButton", forControlEvents: .TouchUpInside)
        removeButton.addTarget(self, action: "clickRemoveButton", forControlEvents: .TouchUpInside)
    }
    
}
//MARK: - cell中的按钮的事件
extension LQPictureViewCell {
    //MARK: - 点击添加按钮的事件
    @objc private func clickAddButton () {

        self.pictureDelegate?.pictureViewCellDidClickAddButton?(self)
    }
    @objc private func clickRemoveButton () {

        self.pictureDelegate?.pictureViewCellDidClickRemoveButton?(self)
    }
    
}
